//
//  WXPayWebViewController.m
//  TestJS2WebView
//
//  Created by hongliang on 16/3/7.
//
//

#import "WXPayWebViewController.h"
#import "TappModel.h"
#import "AFNetManager+wxPay.h"
#import "PayManager.h"
#import "MBProgressHUDManager.h"
#import "UIAlertView+Blocks.h"

extern NSString* const didWeChatPayFinishedNotification;

@interface WXPayWebViewController ()

@property(nonatomic, copy)NSString* userAgentOrigin;

@property(nonatomic, strong)TappModel* tappModel;

@property(nonatomic, copy)NSString* currentTradeNo;

@property(nonatomic, strong)MBProgressHUDManager* HUDManager;
@end

@implementation WXPayWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.HUDManager = [[MBProgressHUDManager alloc] initWithView:self.navigationController.view];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didWeChatPayFinished:) name:didWeChatPayFinishedNotification object:nil];
    
    __weak WXPayWebViewController* wSelf = self;
    self.tappModel = [[TappModel alloc]init];
    self.tappModel.payBlock = ^(NSString* orderId, NSString* paymentAmount) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [wSelf didStartWXPayWithDianKaiOrderId:orderId paymentAmount:[NSString stringWithFormat:@"%.f",[paymentAmount floatValue]*100]];
        });
    };
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.userAgentOrigin = [[[UIWebView alloc] init] stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":[NSString stringWithFormat:@"%@ %@",self.userAgentOrigin,@"tapp(jijiubao)"]}];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":self.userAgentOrigin}];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)showWaiting:(NSString*)waitingMsg {
    //self.HUDManager = [[MBProgressHUDManager alloc] initWithView:self.navigationController.view];
    [self.HUDManager showIndeterminateWithMessage:waitingMsg duration:NSIntegerMax complection:^{
        
    }];
}

- (void)showErrorMessage:(NSString*)errorMsg {
    self.HUDManager = [[MBProgressHUDManager alloc] initWithView:self.navigationController.view];
    [self.HUDManager showErrorWithMessage:errorMsg];
}

#pragma mark - wxPay
- (void)didStartWXPayWithDianKaiOrderId:(NSString*)orderId paymentAmount:(NSString*)paymentAmount {
    NSLog(@"orderId is %@", orderId);
    NSLog(@"paymentAmount is %@", paymentAmount);
    
    [self showWaiting:@"支付中..."];
    __weak WXPayWebViewController* wSelf = self;
    [[AFNetManager sharedInstance] wxPayWithDianKaiOrderId:orderId paymentAmount:paymentAmount finished:^(NSDictionary *dictResult, NSError *error) {
        [wSelf.HUDManager hide];
        
        if (!error) {
            WXPayData* payData = [dictResult objectForKey:HTTPResDataKey];
            wSelf.currentTradeNo = payData.tradeNo;
            [PayManager weChatPay:payData];
        }else {
            [wSelf showErrorMessage:@"获取订单失败"];
        }
    }];
}

- (void)didWeChatPayFinished:(NSNotification*)notification {
    //NSError* error = [[notification userInfo] objectForKey:@"error"];
    
    [self showWaiting:@"获取支付结果中..."];
    __weak WXPayWebViewController* wSelf = self;
    [[AFNetManager sharedInstance] didStartQueryPay:self.currentTradeNo finished:^(NSDictionary *dictResult, NSError *error) {
        [wSelf.HUDManager hide];
               
        [UIAlertView displayAlertWithTitle:[NSString stringWithFormat:@"订单状态%@",[WXPayData payOrderStaus:dictResult]] message:[NSString stringWithFormat:@"%@",dictResult] leftButtonTitle:@"ok" leftButtonAction:nil rightButtonTitle:nil rightButtonAction:nil];
        
        [wSelf js_payCallback];
    }];
}

- (void)js_payCallback {
    [self jsMethod:@"tapp_pay_back" arguments:nil];
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [super webViewDidFinishLoad:webView];
    
    [self registerOCModel:@"Tapp" objc:self.tappModel];
}

@end
